package com.bookquery.dao;
import com.bookquery.util.DatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 执行数据库操作的工具类。
 *
 * @author 北大青鸟
 */
public class BaseDao {

    protected Connection conn;
    protected PreparedStatement pstmt ;
    public BaseDao(Connection conn) {
        this.conn = conn;
    }

    /**
     * 增、删、改操作
     *
     * @param sql sql语句
     * @param
     * @return 执行结果
     * @throws SQLException
     */
    protected int executeUpdate(String sql, Object... params) throws SQLException {
        int result = 0;
        try {
            pstmt = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        } finally {
            DatabaseUtil.closeAll(conn, pstmt, null);
        }
        return result;
    }

    /**
     * 查询操作
     *
     * @param sql    sql语句
     * @param params 参数数组
     * @return 查询结果集
     * @throws SQLException
     */
    protected ResultSet executeQuery(String sql, Object... params) throws SQLException {
        ResultSet rs = null;
        try {
            pstmt = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        }
        return rs;
    }
}
